<template>
  <div class="demo">
    <h1>ProgressDemo</h1>
    <div>
      <button @click="addTask">Add Task</button>
      <button @click="startTask">Start Task</button>
    </div>

    <div class="list">
      <div
          v-for="item in list"
          :key="item.guid"
          class="list-item">
        <div class="name">
          {{ item.name }}
        </div>
        <div class="progress-text">
          {{ item.progress }}%
        </div>
        <div class="progress" :style="{width: `${item.progress}%`}"></div>

      </div>
    </div>
  </div>
</template>

<script>
import {ListItem} from '@/enum'
import {asyncPool, getRandomInt} from '@/utils/util'

export default {
  name: "ProgressDemo",
  data() {
    return {
      list: []
    }
  },
  mounted() {
    let i = 0
    while (i < 10) {
      i++
      this.addTask()
    }
  },
  methods: {
    addTask() {
      this.list.push(new ListItem({
        name: Math.random().toString(36).substr(2)
      }))
    },
    startTask() {
      asyncPool(3, this.list, (item) => {
        console.log(item)
        return new Promise(resolve => {
          const addPercent = () => {
            if (item.progress >= 100) {
              return resolve()
            }
            const p = getRandomInt(1, 5)
            const pp = getRandomInt(2, 10)
            setTimeout(() => {
              item.progress += pp
              addPercent()
            }, p * 100)
          }
          addPercent()
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.list {
  margin-top: 10px;
  border: 1px solid blue;

  .list-item {
    height: 40px;
    padding: 0 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;
    overflow: hidden;

    & + .list-item {
      border-top: 1px solid blue;
    }

    .progress {
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      background: #a1d9a1;
      z-index: -1;
      transition: all .3s;
    }
  }
}
</style>
